<template>
  <!--用户管理页-->
  <div class="user-view">
    <span class="user-view-title">用户管理</span>
    <el-button class="title-right-button" type="primary" @click="handleCreate">新建用户</el-button>
  </div>
  <!--新建/修改用户弹窗-->
  <el-dialog
      :title="dialogTitle"
      class="user-dialog"
      v-model="dialogVisible"
  >
    <el-form
        label-width="80px"
        label-position="top"
    >
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="用户名">
            <el-input
                v-model="user.username"
                :disabled="user.id != null"
                placeholder="请输入用户名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号">
            <el-input v-model="user.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="邮箱">
            <el-input v-model="user.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄">
            <el-input v-model="user.age" placeholder="请输入年龄"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="职级">
            <el-select placeholder="请选择" v-model="user.level" @change="loadLeader">
              <el-option v-for="item in levelOptions" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="直属领导">
            <el-select placeholder="请选择" v-model="user.parentId">
              <el-option v-for="item in leaderOptions" :label="item.username" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="性别">
            <el-radio-group v-model="user.gender">
              <el-radio-button label="男" value="1" style="margin: 0;"></el-radio-button>
              <el-radio-button label="女" value="0"></el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="用户状态">
            <el-switch
                v-model="user.status"
                size="large"
                active-text="启用"
                inactive-text="禁用"
                active-value="1"
                inactive-value="0"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button @click="saveUser" type="primary">保存</el-button>
    </template>
  </el-dialog>
  <el-card class="search-card">
    <el-form :inline="true">
      <el-form-item label="搜索">
        <el-input
            placeholder="输入用户名"
            style="width: 220px;"
            v-model="searchUserForm.username"
            @keydown.enter="loadUser"></el-input>
      </el-form-item>
      <el-form-item label="职级">
        <el-select style="width: 100px;" placeholder="请选择" v-model="searchUserForm.level">
          <el-option :label="item.label" :value="item.value" v-for="item in levelOptions"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select style="width: 100px;" placeholder="请选择" v-model="searchUserForm.status">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearchForm">重置</el-button>
        <el-button type="primary" @click="loadUser">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card class="table-card">
    <el-table :data="searchList" style="width: 100%;" height="600">
      <el-table-column type="index" label="编号" width="80" align="center"/>
      <el-table-column prop="username" label="用户名" align="center"/>
      <el-table-column prop="phone" label="电话号码" align="center"/>
      <el-table-column prop="email" label="邮件" align="center"/>
      <el-table-column prop="createTime" label="创建时间" align="center"/>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-switch
              active-value="1"
              inactive-value="0"
              v-model="scope.row.status"
              @change="changeStatus(scope.row.id, scope.row.status)"
              inline-prompt
              active-text="启用"
              inactive-text="禁用"
              :disabled="scope.row.parentId == null"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
              size="small"
              :disabled="scope.row.parentId == null"
              @click="openResetPasswordConfirmBox(scope.row.id)"
          >密码重置
          </el-button>
          <el-button
              type="primary"
              size="small"
              @click="handleUpdate(scope.row.id)"
              :disabled="scope.row.parentId == null"
          >编辑
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="openDeleteConfirmBox(scope.row.id)"
              :disabled="scope.row.parentId == null"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage, ElMessageBox} from "element-plus";
// 定义变量控制弹窗是否出现
const dialogVisible = ref(false);

const user = ref({
  username: '',
  phone: '',
  email: '',
  age: '',
  level: '',
  parentId: '',
  gender: '1',
  status: ''
});
// 定义数组来维护员工职级的选项
const levelOptions = ref([
  {label: '职员', value: '10'},
  {label: '经理', value: '20'},
  {label: '总监', value: '30'},
  {label: '总裁', value: '40'}
]);
// 定义数组来维护员工直属领导的选项
const leaderOptions = ref([]);
// 保存员工信息
const saveUser = () => {
  let data = qs.stringify(user.value);
  console.log(data);
  axios.post(BASE_URL + '/v1/user/save', data)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('保存成功！');
          window.setTimeout(() => {
            dialogVisible.value = false;
            loadUser();
          }, 1000)
        } else {
          ElMessage.error(response.data.msg);
        }
      })
};
// 取消保存员工信息
const cancel = () => {
  dialogVisible.value = false;
};
// 定义对象来保存用户查询的条件
const searchUserForm = ref({username: '', level: '', status: ''});
// 重置查询条件
const resetSearchForm = () => {
  searchUserForm.value = {};
}
const loadUser = () => {
  let data = qs.stringify(searchUserForm.value);
  console.log(data);
  axios.get(BASE_URL + '/v1/user/select?' + data)
      .then((response) => {
        if (response.data.code == 2000) {
          searchList.value = response.data.data;
        } else {
          ElMessage.error(response.data.msg);
        }
      })
};
// 定义对象保存查询到的用户表格数据
const searchList = ref([]);
//页面加载时立即调用loadUser()
onMounted(() => {
  loadUser();
});
// 定义方法获取直属领导数据
const loadLeader = () => {
  //如果选错了领导,在下次获取的时候需要将上次的数据给清空
  leaderOptions.value = [];
  dialogTitle.value == '修改用户' ? console.log('') : user.value.parentId = '';
  //查询直属领导
  let level = parseInt(user.value.level) + 10;
  axios.get(BASE_URL + '/v1/user/select?level=' + level)
      .then((response) => {
        if (response.data.code == 2000) {
          leaderOptions.value = response.data.data;
        } else {
          ElMessage.error(response.data.msg)
        }
      });
}
//重置密码
const resetPassword = (userId) => {
  axios.post(BASE_URL + '/v1/user/update/password/' + userId)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('密码重置成功！');
        } else {
          ElMessage.error(response.data.msg)
        }
      });
}
//点击重置密码弹出确认提示框 todo 当前用户重置密码后需要重新登录
const openResetPasswordConfirmBox = (userId) => {
  ElMessageBox.confirm(
      '重置密码后该用户将会退出登录,确认重置密码吗?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        resetPassword(userId);
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '操作取消',
        })
      })
}
//点击删除弹出确认提示框
const openDeleteConfirmBox = (userId) => {
  ElMessageBox.confirm(
      '删除后不可恢复,确认删除吗?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        handleDelete(userId);
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '操作取消',
        })
      })
}
// 默认是新建用户标题
const dialogTitle = ref('新建用户');
// 新建用户
const handleCreate = () => {
  dialogTitle.value = '新建用户';
  user.value = {gender: '1'};
  dialogVisible.value = true;
  leaderOptions.value = [];
}
// 修改页面,修改之前先查一次
const handleUpdate = (id) => {
  axios.get(BASE_URL + '/v1/user/select?id=' + id)
      .then((response) => {
        if (response.data.code == 2000) {
          dialogVisible.value = true;
          dialogTitle.value = '修改用户';
          user.value = response.data.data[0];
          loadLeader();
        } else {
          ElMessage.error(response.data.msg)
        }
      });
}
// 删除用户 todo 不能删除当前登录的用户
const handleDelete = (userId) => {
  axios.delete(BASE_URL + '/v1/user/delete/' + userId)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('删除成功!');
          loadUser();
        } else {
          ElMessage.error(response.data.msg)
        }
      });
}
// 修改用户状态 todo 不能禁用当前登录的用户
const changeStatus = (userId, status) => {
  axios.post(BASE_URL + '/v1/user/update/status/' + userId + '/' + status)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('修改成功!');
        } else {
          ElMessage.error(response.data.msg)
        }
      });
}
</script>

<style scoped>
.user-view {
  height: 4vh;
  padding: 5px 20px;
  background-color: #fff;
}

.user-view-title {
  line-height: 40px;
  font-size: 20px;
  font-weight: bold;
}

.title-right-button {
  float: right;
  margin-top: 3px;
}

.user-dialog {
  width: 1000px;
  padding: 40px;
}

.search-card {
  margin: 20px;
  height: 70px;
}

.table-card {
  margin: 20px;
}
</style>